package kr.co.webmill;

import java.util.List;
import java.util.Random;

import kr.co.webmill.testdatabase.Comment;
import kr.co.webmill.R;
import kr.co.webmill.R.id;
import kr.co.webmill.R.layout;
import kr.co.webmill.R.menu;
import kr.co.webmill.sqlite.CommentsDataSource;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TestDatabaseActivity extends Activity {
	ListView dbListView;
	ArrayAdapter<Comment> cAdapter;
	CommentsDataSource dataSource = new CommentsDataSource(this);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		dataSource.open();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test_database);
//		debugDialog("view end");
		List<Comment> allList = dataSource.getAllComments();
		cAdapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, allList);
		dbListView = (ListView) findViewById(R.id.dbList);
		dbListView.setAdapter(cAdapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_test_database, menu);
		return true;
	}
	// button click
	public void onClick(View view){
		Comment comment;
		switch(view.getId()){
		case (R.id.add) :
			String[] comments = new String[] {"Cool", "Very nice", "Hate it"};
			int nextInt = new Random().nextInt(3);
			comment = dataSource.createComment(comments[nextInt]);
			cAdapter.add(comment);
			break;
		case (R.id.delete) :
			comment  = cAdapter.getItem(0);
			dataSource.deleteComment(comment);
			cAdapter.remove(comment);
			break;
		default :
			break;
		}
		cAdapter.notifyDataSetChanged();
		
	}
	@Override
	protected void onPause() {
		dataSource.close();
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		dataSource.open();
		super.onResume();
	}	
	public void debugDialog(String str){
		AlertDialog.Builder ad = new AlertDialog.Builder(TestDatabaseActivity.this);
		ad.setTitle("Debug Dialog");
		ad.setMessage(str);
		ad.setPositiveButton("OK", new OnClickListener (){
			public void onClick(DialogInterface dialog, int arg1) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
		ad.setCancelable(true);
		ad.setOnCancelListener(new OnCancelListener(){

			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
			
		});
		ad.show();
	}
}
